{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Quantum Classifier\n",
    "\n",
    "<em> Copyright (c) 2021 Institute for Quantum Computing, Baidu Inc. All Rights Reserved. </em>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Overview\n",
    "\n",
    "In this tutorial, we will discuss the workflow of Variational Quantum Classifiers (VQC) and how to use quantum neural networks (QNN) to accomplish a **binary classification** task. The main representatives of this approach include the [Quantum Circuit Learning (QCL)](https://arxiv.org/abs/1803.00745) [1] by Mitarai et al. (2018), Farhi & Neven ( 2018) [2] and [Circuit-Centric Quantum Classifiers](https://arxiv.org/abs/1804.00633) [3] by Schuld et al. (2018). Here, we mainly talk about classification in the language of supervised learning. Unlike classical methods, quantum classifiers require pre-processing to encode classical data into quantum data, and then train the parameters in the quantum neural network. Finally, we benchmark the optimal classification performance through test data.\n",
    "\n",
    "### Background\n",
    "\n",
    "In the language of supervised learning, we need to enter a data set composed of $N$ groups of labeled data points $D = \\{(x^k,y^k)\\}_{k=1}^{N}$ , Where $x^k\\in \\mathbb{R}^{m}$ is the data point, and $y^k \\in\\{0,1\\}$ is the label associated with the data point $x^k$. **The classification process is essentially a decision-making process, which determines the label attribution of a given data point**. For the quantum classifier framework, the realization of the classifier $\\mathcal{F}$ is a combination of a quantum neural network (or parameterized quantum circuit) with parameters $\\theta$, measurement, and data processing. An excellent classifier $\\mathcal{F}_\\theta$ should correctly map the data points in each data set to the corresponding labels as accurate as possible $\\mathcal{F}_\\theta(x^k ) \\rightarrow y^k$. Therefore, we use the cumulative distance between the predicted label $\\tilde{y}^{k} = \\mathcal{F}_\\theta(x^k)$ and the actual label $y^k$ as the loss function $\\mathcal {L}(\\theta)$ to be optimized. For binary classification tasks, we can choose the following loss function,\n",
    "\n",
    "$$\n",
    "\\mathcal{L}(\\theta) = \\sum_{k=1}^N |\\tilde{y}^{k}-y^k|^2. \\tag{1}\n",
    "$$\n",
    "\n",
    "### Pipeline\n",
    "\n",
    "Here we give the whole pipeline to implement a quantum classifier under the framework of quantum circuit learning (QCL).\n",
    "\n",
    "1. Apply the parameterized quantum circuit $U$ on the initialized qubit $\\lvert 0 \\rangle$ to encode the original classical data point $x^k$ into quantum data that can be processed on a quantum computer $\\lvert \\psi_{in}\\rangle^k$.\n",
    "2. Apply the parameterized circuit $U(\\theta)$ with the parameter $\\theta$ on input states $\\lvert \\psi_{in} \\rangle^k$, thereby obtaining the output state $\\lvert \\psi_{out} \\rangle^k = U(\\theta)\\lvert \\psi_{in} \\rangle^k$.\n",
    "3. Measure the quantum state $\\lvert \\psi_{out}\\rangle^k$ processed by the quantum neural network to get the estimated label $\\tilde{y}^{k}$.\n",
    "4. Repeat steps 2-3 until all data points in the data set have been processed. Then calculate the loss function $\\mathcal{L}(\\theta)$.\n",
    "5. Continuously adjust the parameter $\\theta$ through optimization methods such as gradient descent to minimize the loss function. Record the optimal parameters after optimization $\\theta^* $, and then we obtain the optimal classifier $\\mathcal{F}_{\\theta^*}$.\n",
    "\n",
    "![QCL](figures/qclassifier-fig-pipeline.png \"Figure 1: Flow chart of quantum classifier training\")\n",
    "<div style=\"text-align:center\">Figure 1: Flow chart of quantum classifier training </div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Paddle Quantum Implementation\n",
    "\n",
    "Here, we first import the required packages:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:03:35.665758Z",
     "start_time": "2021-03-09T04:03:32.186676Z"
    }
   },
   "outputs": [],
   "source": [
    "import time\n",
    "import matplotlib\n",
    "import numpy as np\n",
    "import paddle\n",
    "from numpy import pi as PI\n",
    "from matplotlib import pyplot as plt\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "from paddle import matmul, transpose\n",
    "from paddle_quantum.circuit import UAnsatz\n",
    "from paddle_quantum.utils import pauli_str_to_matrix"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:03:35.682126Z",
     "start_time": "2021-03-09T04:03:35.668825Z"
    }
   },
   "outputs": [],
   "source": [
    "# These are the main functions that will be used in the tutorial\n",
    "__all__ = [\n",
    "    \"circle_data_point_generator\",\n",
    "    \"data_point_plot\",\n",
    "    \"heatmap_plot\",\n",
    "    \"Ry\",\n",
    "    \"Rz\",\n",
    "    \"Observable\",\n",
    "    \"U_theta\",\n",
    "    \"Net\",\n",
    "    \"QC\",\n",
    "    \"main\",\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data set generation\n",
    "\n",
    "One of the key parts in supervised learning is what data set to use? In this tutorial, we follow the exact approach introduced in QCL paper to generate a simple binary data set $\\{(x^{(i)}, y^{(i)})\\}$ with circular decision boundary, where the data point $x^{(i)}\\in \\mathbb{R}^{2}$, and the label $y^{(i)} \\in \\{0,1\\}$. The figure below provides us a concrete example.\n",
    "\n",
    "![QC-fig-data](./figures/qclassifier-fig-data.png \"Figure 2: Generated data set and the corresponding decision boundary\")\n",
    "<div style=\"text-align:center\">Figure 2: Generated data set and the corresponding decision boundary </div>\n",
    "\n",
    "For the generation method and visualization, please see the following code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:03:35.707224Z",
     "start_time": "2021-03-09T04:03:35.691351Z"
    }
   },
   "outputs": [],
   "source": [
    "# Generate a binary classification data set with circular decision boundary\n",
    "def circle_data_point_generator(Ntrain, Ntest, boundary_gap, seed_data):\n",
    "    \"\"\"\n",
    "    :param Ntrain: number of training samples\n",
    "    :param Ntest: number of test samples\n",
    "    :param boundary_gap: value in (0, 0.5), means the gap between two labels\n",
    "    :param seed_data: random seed\n",
    "    :return: 'Ntrain' samples for training and\n",
    "             'Ntest' samples for testing\n",
    "    \"\"\"\n",
    "    train_x, train_y = [], []\n",
    "    num_samples, seed_para = 0, 0\n",
    "    while num_samples < Ntrain + Ntest:\n",
    "        np.random.seed((seed_data + 10) * 1000 + seed_para + num_samples)\n",
    "        data_point = np.random.rand(2) * 2 - 1\n",
    "\n",
    "        # If the modulus of the data point is less than (0.7 - gap), mark it as 0\n",
    "        if np.linalg.norm(data_point) < 0.7-boundary_gap / 2:\n",
    "            train_x.append(data_point)\n",
    "            train_y.append(0.)\n",
    "            num_samples += 1\n",
    "\n",
    "        # If the modulus of the data point is greater than (0.7 + gap), mark it as 1\n",
    "        elif np.linalg.norm(data_point) > 0.7 + boundary_gap / 2:\n",
    "            train_x.append(data_point)\n",
    "            train_y.append(1.)\n",
    "            num_samples += 1\n",
    "        else:\n",
    "            seed_para += 1\n",
    "\n",
    "    train_x = np.array(train_x).astype(\"float64\")\n",
    "    train_y = np.array([train_y]).astype(\"float64\").T\n",
    "\n",
    "    print(\"The dimensions of the training set x {} and y {}\".format(np.shape(train_x[0:Ntrain]), np.shape(train_y[0:Ntrain])))\n",
    "    print(\"The dimensions of the test set x {} and y {}\".format(np.shape(train_x[Ntrain:]), np.shape(train_y[Ntrain:])), \"\\n\")\n",
    "\n",
    "    return train_x[0:Ntrain], train_y[0:Ntrain], train_x[Ntrain:], train_y[Ntrain:]\n",
    "\n",
    "\n",
    "# Visualize the generated data set\n",
    "def data_point_plot(data, label):\n",
    "    \"\"\"\n",
    "    :param data: shape [M, 2], means M 2-D data points\n",
    "    :param label: value 0 or 1\n",
    "    :return: plot these data points\n",
    "    \"\"\"\n",
    "    dim_samples, dim_useless = np.shape(data)\n",
    "    plt.figure(1)\n",
    "    for i in range(dim_samples):\n",
    "        if label[i] == 0:\n",
    "            plt.plot(data[i][0], data[i][1], color=\"r\", marker=\"o\")\n",
    "        elif label[i] == 1:\n",
    "            plt.plot(data[i][0], data[i][1], color=\"b\", marker=\"o\")\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:03:37.244233Z",
     "start_time": "2021-03-09T04:03:35.719425Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The dimensions of the training set x (200, 2) and y (200, 1)\n",
      "The dimensions of the test set x (100, 2) and y (100, 1) \n",
      "\n",
      "Visualization of 200 data points in the training set: \n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAD4CAYAAADhNOGaAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAoeklEQVR4nO2df6weV5nfP49fY2kNlCbXJjg/fJ1IESJZAU2uIgIrlnQJm3hLA9UiQZ3Uu0W1fAXSsupu5chSFRVZZam620BJu27Wkpt7C6pU2ETUaQjZRduCFriJEsdp6vwiP4xT4jiwLAIV4pz+MfNyx6/n98yZOfPO9yMdvfN7nnfmzHnOOc9znmPOOYQQQoyXDX0LIIQQol+kCIQQYuRIEQghxMiRIhBCiJEjRSCEECNnY98C1GHLli1ux44dfYshhBCD4sEHH3zZObd1dvsgFcGOHTtYW1vrWwwhhBgUZvZc2nZ1DQkhxMiRIhBCiJEjRSCEECNHikAIIUaOFIEQQoycVhSBmR0ys5fM7FjGfjOzz5nZU2Z21MyuSuy7wcyOx/v2tSGPEHVYXYUdO2DDhuh3dbVvicIk9OcUinyhyFEK51zjBLwXuAo4lrF/J3AvYMC7gG/H2yfA08BlwCbgEeCKovtdffXVbsisrDi3uOicWfS7stK3RGJlxbnNm52D9bR5s97NLL6eU1vfRCjvMRQ5ZgHWXFoZnbaxTgJ25CiCPwU+llg/DmwDrgXuS2y/Fbi16F5DVgRpGQScW1joP5P4JHTlt7h47juBaLtYx8dzarPQDOU9hiLHLFmKoCsbwUXAC4n1E/G2rO3nYGZ7zGzNzNZOnTrlTVDf7N8PP/3pudtPn4Y9e9ptPobS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607gh4nns1b0XjuS65PxfR8hMmK/u4vnVUa2eP13gC/NnOftmRFV/l4EfkFUhn28q/ylEBNCCDFyxto1JIQQIkaKQAghRo4UgRBCjBwpAiGEGDlSBEIIMXKkCIQQYuRIEQghxMj5/w62GGID6HZlAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Visualization of 100 data points in the test set: \n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYIAAAD4CAYAAADhNOGaAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAgsklEQVR4nO3df+xdd33f8efLDpEwRJA4TnB+fZ1WGVqoSkq+Mj9atSBIl7iiBmloSb9QT2PysimoTGu3ZJFQtMoSo6MTVJTKUISJvyJiApqoGEJgZSlDQL6J8sNpauJYjmPsJd84CJoRLU383h/nXHx8fX+c+73n93k9pKt77/lxz+eee+55f87n11FEYGZm/bWu7gSYmVm9HAjMzHrOgcDMrOccCMzMes6BwMys586qOwFrcf7558eWLVvqToaZWavcf//9z0bEpuHprQwEW7ZsYWVlpe5kmJm1iqQnR0130ZCZWc85EJiZ9ZwDgZlZzzkQmJn1nAOBmVnPFRIIJH1O0jOS9o+ZL0mflHRQ0sOS3pSZd62kA+m8m4tIj5nNZ3kZtmyBdeuS5+XlulNkZSrqiuDzwLUT5l8HXJE+dgKfBpC0HvhUOv9K4AZJVxaUJjNbg+Vl2LkTnnwSIpLnnTsdDLqskEAQEfcCz01YZDvwhUh8H3itpM3AVuBgRByKiBeBO9JlW8s5KWu7W2+Fn//89Gk//3ky3bqpqjqCi4GnMu+PptPGTT+DpJ2SViStrK6ulpbQeTgnZV1w5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L5x8DHgX9VYbp+PSKOSboAuEfS36c5mDUrcH+9muTP+uGI+Fk6ec37a9QmRkwbPl7GLVPKsZZju2cuKL2DJBD8RmZy4b/rDOl6gKTo8/m0DuevgCtyrltmugbeDfzviMjm0svaX3mUcoy1NhBEQ+6lPEu6JM3yudcBD0TE05nP/sVrSZ8B/rrKdEXEsfT5GUlfJbkcvZea95ekV5AEgeWI+Erms9e8v0aYdLxMW+bsHOvOI0/akPSrwGeB6yLixGD6hN+19HRlgjYRsU/Sn0s6P8+6ZaYr44yr8hL3Vx6lHGN9Lhq6D7hC0uVp7vt64K503l3AjvT1DiDPFUYes3zuGeWS6clw4L3AyJYFZaRL0qsknTN4Dfx2Zvu17S9JAv4SeCwi/nRoXpH7a9Lxkk3v76ctO94C/DQt0sqz7jymfr6ky4CvAB+IiB9lpk/6XatI1+vS3xBJW0nOSSfyrFtmutL0vAb4LTLHXcn7K49yjrEyar7rfpD86Y8C/w94Grg7nX4RsC+z3DaSViZPkBQpDaZvBL4NPJ4+n1dQukZ+7oh0bSD5M7xmaP3bgUeAh9MfeXNV6SJpjfBQ+ni0KfuLpIgj0n3yYPrYVsb+GnW8ADcCN6avBXwqnf8ImRZr4461Ao/5aWn7LPCTzD5amfa7VpSum9LtPkRSif22KvbZtHSl7/8lcMfQemXvry8Cx4F/JDmHfbCKY8xDTJiZ9Vyfi4bMzAwHAjOz3nMgMDPrOQcCM7OecyAwM+s5BwIzs55zIDAz67n/D8qKOkqmMigOAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      " You may wish to adjust the parameter settings to generate your own data set!\n"
     ]
    }
   ],
   "source": [
    "# Set parameters\n",
    "Ntrain = 200       # Specify the training set size\n",
    "Ntest = 100        # Specify the test set size\n",
    "boundary_gap = 0.5 # Set the width of the decision boundary\n",
    "seed_data = 2      # Fixed random seed\n",
    "\n",
    "# Generate data set\n",
    "train_x, train_y, test_x, test_y = circle_data_point_generator(\n",
    "        Ntrain, Ntest, boundary_gap, seed_data)\n",
    "print(\"Visualization of {} data points in the training set: \".format(Ntrain))\n",
    "data_point_plot(train_x, train_y)\n",
    "print(\"Visualization of {} data points in the test set: \".format(Ntest))\n",
    "data_point_plot(test_x, test_y)\n",
    "print(\"\\n You may wish to adjust the parameter settings to generate your own data set!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Data preprocessing\n",
    "Different from classical machine learning, quantum classifiers need to consider data preprocessing heavily. We need one more step to convert classical data into quantum information before running on a quantum computer. Now let's take a look at how it can be done. First, we determine the number of qubits that need to be used. Because our data $\\{x^{(i)} = (x^{(i)}_0, x^{(i)}_1)\\}$ is two-dimensional, according to the paper by Mitarai (2018) we need at least 2 qubits for encoding. Then prepare a group of initial quantum states $|00\\rangle$. Encode the classical information $\\{x^{(i)}\\}$ into a group of quantum gates $U(x^{(i)})$ and act them on the initial quantum states. Finally we get a group of quantum states $|\\psi^{(i)}\\rangle = U(x^{(i)})|00\\rangle$. In this way, we have completed the encoding from classical information into quantum information! Given $m$ qubits to encode a two-dimensional classical data point, the quantum gate is:\n",
    "\n",
    "$$\n",
    "U(x^{(i)}) = \\otimes_{j=0}^{m-1} R_j^z\\big[\\arccos(x^{(i)}_{j \\, \\text{mod} \\, 2}\\cdot x^{(i)}_{j \\, \\text{mod} \\, 2})\\big] R_j^y\\big[\\arcsin(x^{(i)}_{j \\, \\text{mod} \\, 2}) \\big],\n",
    "\\tag{2}\n",
    "$$\n",
    "\n",
    "**Note:** In this representation, we count the first qubit as $j = 0$. For more encoding methods, see [Robust data encodings for quantum classifiers](https://arxiv.org/pdf/2003.01695.pdf). We also provide several built-in [encoding methods](./DataEncoding_EN.ipynb) in Paddle Quantum. Here we also encourage readers to try new encoding methods by themselves!\n",
    "\n",
    "Since this encoding method looks quite complicated, we might as well give a simple example. Suppose we are given a data point $x = (x_0, x_1)= (1,0)$. The label of this data point should be 1, corresponding to the **blue** point in the figure above. At the same time, the 2-qubit quantum gate $U(x)$ corresponding to the data point is,\n",
    "\n",
    "$$\n",
    "U(x) =\n",
    "\\bigg( R_0^z\\big[\\arccos(x_{0}\\cdot x_{0})\\big] R_0^y\\big[\\arcsin(x_{0}) \\big] \\bigg)\n",
    "\\otimes\n",
    "\\bigg( R_1^z\\big[\\arccos(x_{1}\\cdot x_{1})\\big] R_1^y\\big[\\arcsin(x_{1}) \\big] \\bigg),\n",
    "\\tag{3}\n",
    "$$\n",
    "\n",
    "Substituting in specific values, we get:\n",
    "\n",
    "$$\n",
    "U(x) =\n",
    "\\bigg( R_0^z\\big[0\\big] R_0^y\\big[\\pi/2 \\big] \\bigg)\n",
    "\\otimes\n",
    "\\bigg( R_1^z\\big[\\pi/2\\big] R_1^y\\big[0 \\big] \\bigg),\n",
    "\\tag{4}\n",
    "$$\n",
    "\n",
    "Recall the matrix form of rotation gates:\n",
    "\n",
    "$$\n",
    "R_x(\\theta) :=\n",
    "\\begin{bmatrix}\n",
    "\\cos \\frac{\\theta}{2} &-i\\sin \\frac{\\theta}{2} \\\\\n",
    "-i\\sin \\frac{\\theta}{2} &\\cos \\frac{\\theta}{2}\n",
    "\\end{bmatrix}\n",
    ",\\quad\n",
    "R_y(\\theta) :=\n",
    "\\begin{bmatrix}\n",
    "\\cos \\frac{\\theta}{2} &-\\sin \\frac{\\theta}{2} \\\\\n",
    "\\sin \\frac{\\theta}{2} &\\cos \\frac{\\theta}{2}\n",
    "\\end{bmatrix}\n",
    ",\\quad\n",
    "R_z(\\theta) :=\n",
    "\\begin{bmatrix}\n",
    "e^{-i\\frac{\\theta}{2}} & 0 \\\\\n",
    "0 & e^{i\\frac{\\theta}{2}}\n",
    "\\end{bmatrix}.\n",
    "\\tag{5}\n",
    "$$\n",
    "\n",
    "Then the matrix form of the two-qubit quantum gate $U(x)$ can be written as\n",
    "\n",
    "$$\n",
    "U(x) = \n",
    "\\bigg(\n",
    "\\begin{bmatrix}\n",
    "1 & 0 \\\\ \n",
    "0 & 1\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    "\\cos \\frac{\\pi}{4} &-\\sin \\frac{\\pi}{4} \\\\ \n",
    "\\sin \\frac{\\pi}{4} &\\cos \\frac{\\pi}{4} \n",
    "\\end{bmatrix}\n",
    "\\bigg)\n",
    "\\otimes \n",
    "\\bigg(\n",
    "\\begin{bmatrix}\n",
    "e^{-i\\frac{\\pi}{4}} & 0 \\\\ \n",
    "0 & e^{i\\frac{\\pi}{4}}\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    "1 &0 \\\\ \n",
    "0 &1\n",
    "\\end{bmatrix}\n",
    "\\bigg),\n",
    "\\tag{6}\n",
    "$$\n",
    "\n",
    "After simplification, we can get the encoded quantum state $|\\psi\\rangle$ by acting the quantum gate on the initialized quantum state $|00\\rangle$,\n",
    "\n",
    "$$\n",
    "|\\psi\\rangle =\n",
    "U(x)|00\\rangle = \\frac{1}{2}\n",
    "\\begin{bmatrix}\n",
    "1-i &0 &-1+i &0 \\\\\n",
    "0 &1+i &0 &-1-i \\\\\n",
    "1-i &0 &1-i &0 \\\\\n",
    "0 &1+i &0 &1+i\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    "1 \\\\\n",
    "0 \\\\\n",
    "0 \\\\\n",
    "0\n",
    "\\end{bmatrix}\n",
    "= \\frac{1}{2}\n",
    "\\begin{bmatrix}\n",
    "1-i \\\\\n",
    "0 \\\\\n",
    "1-i \\\\\n",
    "0\n",
    "\\end{bmatrix}.\n",
    "\\tag{7}\n",
    "$$\n",
    "\n",
    "Then let us take a look at how to implement this encoding method in Paddle Quantum. Note that in the code, we use the following trick: \n",
    "\n",
    "$$\n",
    "(U_1 |0\\rangle)\\otimes (U_2 |0\\rangle) = (U_1 \\otimes U_2) |0\\rangle\\otimes|0\\rangle\n",
    "= (U_1 \\otimes U_2) |00\\rangle.\n",
    "\\tag{8}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:03:37.354267Z",
     "start_time": "2021-03-09T04:03:37.258314Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "As a test, we enter the classical information:\n",
      "(x_0, x_1) = (1, 0)\n",
      "The 2-qubit quantum state output after encoding is:\n",
      "[[[0.5-0.5j 0. +0.j  0.5-0.5j 0. +0.j ]]]\n"
     ]
    }
   ],
   "source": [
    "def myRy(theta):\n",
    "    \"\"\"\n",
    "    :param theta: parameter\n",
    "    :return: Y rotation matrix\n",
    "    \"\"\"\n",
    "    return np.array([[np.cos(theta / 2), -np.sin(theta / 2)],\n",
    "                     [np.sin(theta / 2), np.cos(theta / 2)]])\n",
    "\n",
    "def myRz(theta):\n",
    "    \"\"\"\n",
    "    :param theta: parameter\n",
    "    :return: Z rotation matrix\n",
    "    \"\"\"\n",
    "    return np.array([[np.cos(theta / 2) - np.sin(theta / 2) * 1j, 0],\n",
    "                     [0, np.cos(theta / 2) + np.sin(theta / 2) * 1j]])\n",
    "\n",
    "# Classical -> Quantum Data Encoder\n",
    "def datapoints_transform_to_state(data, n_qubits):\n",
    "    \"\"\"\n",
    "    :param data: shape [-1, 2]\n",
    "    :param n_qubits: the number of qubits to which\n",
    "    the data transformed\n",
    "    :return: shape [-1, 1, 2 ^ n_qubits]\n",
    "    \"\"\"\n",
    "    dim1, dim2 = data.shape\n",
    "    res = []\n",
    "    for sam in range(dim1):\n",
    "        res_state = 1.\n",
    "        zero_state = np.array([[1, 0]])\n",
    "        for i in range(n_qubits):\n",
    "            if i % 2 == 0:\n",
    "                state_tmp=np.dot(zero_state, myRy(np.arcsin(data[sam][0])).T)\n",
    "                state_tmp=np.dot(state_tmp, myRz(np.arccos(data[sam][0] ** 2)).T)\n",
    "                res_state=np.kron(res_state, state_tmp)\n",
    "            elif i% 2 == 1:\n",
    "                state_tmp=np.dot(zero_state, myRy(np.arcsin(data[sam][1])).T)\n",
    "                state_tmp=np.dot(state_tmp, myRz(np.arccos(data[sam][1] ** 2)).T)\n",
    "                res_state=np.kron(res_state, state_tmp)\n",
    "        res.append(res_state)\n",
    "\n",
    "    res = np.array(res)\n",
    "    return res.astype(\"complex128\")\n",
    "\n",
    "print(\"As a test, we enter the classical information:\")\n",
    "print(\"(x_0, x_1) = (1, 0)\")\n",
    "print(\"The 2-qubit quantum state output after encoding is:\")\n",
    "print(datapoints_transform_to_state(np.array([[1, 0]]), n_qubits=2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Building Quantum Neural Network \n",
    "After completing the encoding from classical data to quantum data, we can now input these quantum states into the quantum computer. Before that, we also need to design the quantum neural network.\n",
    "\n",
    "![QC-fig-classifier_circuit](figures/qclassifier-fig-circuit.png)\n",
    "\n",
    "For convenience, we call the parameterized quantum neural network as $U(\\boldsymbol{\\theta})$. $U(\\boldsymbol{\\theta})$ is a key component of our classifier, and it needs a certain complex structure to fit our decision boundary. Similar to traditional neural networks, the structure of a quantum neural network is not unique. The structure shown above is just one case. You could design your own structure. Let’s take the previously mentioned data point $x = (x_0, x_1)= (1,0)$ as an example. After encoding, we have obtained a quantum state $|\\psi\\rangle$,\n",
    "\n",
    "$$\n",
    "|\\psi\\rangle =\n",
    "\\frac{1}{2}\n",
    "\\begin{bmatrix}\n",
    "1-i \\\\\n",
    "0 \\\\\n",
    "1-i \\\\\n",
    "0\n",
    "\\end{bmatrix}.\n",
    "\\tag{9}\n",
    "$$\n",
    "\n",
    "Then we input this quantum state into our quantum neural network (QNN). That is, multiply a unitary matrix by a vector to get the processed quantum state $|\\varphi\\rangle$\n",
    "\n",
    "$$\n",
    "|\\varphi\\rangle = U(\\boldsymbol{\\theta})|\\psi\\rangle.\n",
    "\\tag{10}\n",
    "$$\n",
    "\n",
    "If we set all the QNN parameters to be $\\theta = \\pi$, then we can write down the resulting state:\n",
    "\n",
    "$$\n",
    "|\\varphi\\rangle =\n",
    "U(\\boldsymbol{\\theta} =\\pi)|\\psi\\rangle =\n",
    "\\begin{bmatrix}\n",
    "0 &0 &-1 &0 \\\\\n",
    "-1 &0 &0 &0 \\\\\n",
    "0 &1 &0 &0 \\\\\n",
    "0 &0 &0 &1\n",
    "\\end{bmatrix}\n",
    "\\cdot\n",
    "\\frac{1}{2}\n",
    "\\begin{bmatrix}\n",
    "1-i \\\\\n",
    "0 \\\\\n",
    "1-i \\\\\n",
    "0\n",
    "\\end{bmatrix}\n",
    "= \\frac{1}{2}\n",
    "\\begin{bmatrix}\n",
    "-1+i \\\\\n",
    "-1+i \\\\\n",
    "0 \\\\\n",
    "0\n",
    "\\end{bmatrix}.\n",
    "\\tag{11}\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:03:37.426687Z",
     "start_time": "2021-03-09T04:03:37.374976Z"
    }
   },
   "outputs": [],
   "source": [
    "# Simulation of building a quantum neural network\n",
    "def U_theta(theta, n, depth):\n",
    "    \"\"\"\n",
    "    :param theta: dim: [n, depth + 3]\n",
    "    :param n: number of qubits\n",
    "    :param depth: circuit depth\n",
    "    :return: U_theta\n",
    "    \"\"\"\n",
    "    # Initialize the network\n",
    "    cir = UAnsatz(n)\n",
    "    \n",
    "    # Build a rotation layer\n",
    "    for i in range(n):\n",
    "        cir.rz(theta[i][0], i)\n",
    "        cir.ry(theta[i][1], i)\n",
    "        cir.rz(theta[i][2], i)\n",
    "\n",
    "    # The default depth is depth = 1\n",
    "    # Build the entangleed layer and Ry rotation layer\n",
    "    for d in range(3, depth + 3):\n",
    "        for i in range(n - 1):\n",
    "            cir.cnot([i, i + 1])\n",
    "        cir.cnot([n - 1, 0])\n",
    "        for i in range(n):\n",
    "            cir.ry(theta[i][d], i)\n",
    "\n",
    "    return cir"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Measurement and loss function\n",
    "After the initial quantum state, $|\\psi\\rangle$ has been processed with QNN on the quantum computer (QPU), we need to measure this new quantum state $|\\varphi\\rangle$ to obtain the classical information. These processed classical information can be used to calculate the loss function $\\mathcal{L}(\\boldsymbol{\\theta})$. Finally, we use the classical computer (CPU) to continuously update the QNN parameters $\\boldsymbol{\\theta}$ and optimize the loss function. Here we measure the expected value of the Pauli $Z$ operator on the first qubit. Specifically,\n",
    "\n",
    "$$\n",
    "\\langle Z \\rangle =\n",
    "\\langle \\varphi |Z\\otimes I\\cdots \\otimes I| \\varphi\\rangle.\n",
    "\\tag{12}\n",
    "$$\n",
    "\n",
    "Recall that the matrix of the Pauli $Z$ operator is defined as:\n",
    "\n",
    "$$\n",
    "Z := \\begin{bmatrix} 1 &0 \\\\ 0 &-1 \\end{bmatrix}.\n",
    "\\tag{13}\n",
    "$$\n",
    "\n",
    "Continuing our previous 2-qubit example, the expected value we get after the measurement is\n",
    "\n",
    "$$\n",
    "\\langle Z \\rangle =\n",
    "\\langle \\varphi |Z\\otimes I| \\varphi\\rangle =\n",
    "\\frac{1}{2}\n",
    "\\begin{bmatrix}\n",
    "-1-i \\quad\n",
    "-1-i \\quad\n",
    "0 \\quad\n",
    "0\n",
    "\\end{bmatrix}\n",
    "\\begin{bmatrix}\n",
    "1 &0 &0 &0 \\\\\n",
    "0 &1 &0 &0 \\\\\n",
    "0 &0 &-1 &0 \\\\\n",
    "0 &0 &0 &-1\n",
    "\\end{bmatrix}\n",
    "\\cdot\n",
    "\\frac{1}{2}\n",
    "\\begin{bmatrix}\n",
    "-1+i \\\\\n",
    "-1+i \\\\\n",
    "0 \\\\\n",
    "0\n",
    "\\end{bmatrix}\n",
    "= 1. \\tag{14}\n",
    "$$\n",
    "\n",
    "This measurement result seems to be our original label 1. Does this mean that we have successfully classified this data point? This is not the case because the range of $\\langle Z \\rangle$ is usually between $[-1,1]$. To match it to our label range $y^{(i)} \\in \\{0,1\\}$, we need to map the upper and lower limits. The simplest mapping is \n",
    "\n",
    "$$\n",
    "\\tilde{y}^{(i)} = \\frac{\\langle Z \\rangle}{2} + \\frac{1}{2} + bias \\quad \\in [0, 1].\n",
    "\\tag{15}\n",
    "$$\n",
    "\n",
    "Using bias is a trick in machine learning. The purpose is to make the decision boundary not restricted by the origin or some hyperplane. Generally, the default bias is initialized to be 0, and the optimizer will continuously update it like all the other parameters $\\theta$ in the iterative process to ensure $\\tilde{y}^{k} \\in [0, 1]$. Of course, you can also choose other complex mappings (activation functions), such as the sigmoid function. After mapping, we can regard $\\tilde{y}^{k}$ as the label we estimated. $\\tilde{y}^{k}< 0.5$ corresponds to label 0, and $\\tilde{y}^{k}> 0.5$ corresponds to label 1. It's time to quickly review the whole process before we finish discussion,\n",
    "\n",
    "$$\n",
    "x^{(i)} \\rightarrow |\\psi\\rangle^{(i)} \\rightarrow U(\\boldsymbol{\\theta})|\\psi\\rangle^{(i)} \\rightarrow\n",
    "|\\varphi\\rangle^{(i)} \\rightarrow ^{(i)}\\langle \\varphi |Z\\otimes I\\cdots \\otimes I| \\varphi\\rangle^{(i)}\n",
    "\\rightarrow \\langle Z \\rangle  \\rightarrow \\tilde{y}^{(i)}. \\tag{16}\n",
    "$$\n",
    "\n",
    "Finally, we can define the loss function as a square loss function:\n",
    "\n",
    "$$\n",
    "\\mathcal{L} = \\sum_{(i)} |y^{(i)}-\\tilde{y}^{(i)}|^2. \\tag{17}\n",
    "$$\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:03:37.439183Z",
     "start_time": "2021-03-09T04:03:37.432202Z"
    }
   },
   "outputs": [],
   "source": [
    "# Generate Pauli Z operator that only acts on the first qubit\n",
    "# Act the identity matrix on rest of the qubits\n",
    "def Observable(n):\n",
    "    \"\"\"\n",
    "    :param n: number of qubits\n",
    "    :return: local observable: Z \\otimes I \\otimes ...\\otimes I\n",
    "    \"\"\"\n",
    "    Ob = pauli_str_to_matrix([[1.0,'z0']], n)\n",
    "    return Ob"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:03:37.503213Z",
     "start_time": "2021-03-09T04:03:37.473028Z"
    }
   },
   "outputs": [],
   "source": [
    "# Build the computational graph\n",
    "class Net(paddle.nn.Layer):\n",
    "    \"\"\"\n",
    "    Construct the model net\n",
    "    \"\"\"\n",
    "    def __init__(self,\n",
    "                 n, # number of qubits\n",
    "                 depth, # circuit depth\n",
    "                 seed_paras=1,\n",
    "                 dtype='float64'):\n",
    "        super(Net, self).__init__()\n",
    "\n",
    "        self.n = n\n",
    "        self.depth = depth\n",
    "        \n",
    "        # Initialize the parameters theta with a uniform distribution of [0, 2*pi]\n",
    "        self.theta = self.create_parameter(\n",
    "            shape=[n, depth + 3],\n",
    "            default_initializer=paddle.nn.initializer.Uniform(low=0.0, high=2*PI),\n",
    "            dtype=dtype,\n",
    "            is_bias=False)\n",
    "        \n",
    "        # Initialize bias\n",
    "        self.bias = self.create_parameter(\n",
    "            shape=[1],\n",
    "            default_initializer=paddle.nn.initializer.Normal(std=0.01),\n",
    "            dtype=dtype,\n",
    "            is_bias=False)\n",
    "\n",
    "    # Define forward propagation mechanism, and then calculate loss function and cross-validation accuracy\n",
    "    def forward(self, state_in, label):\n",
    "        \"\"\"\n",
    "        Args:\n",
    "            state_in: The input quantum state, shape [-1, 1, 2^n]\n",
    "            label: label for the input state, shape [-1, 1]\n",
    "        Returns:\n",
    "            The loss:\n",
    "                L = ((<Z> + 1)/2 + bias-label)^2\n",
    "        \"\"\"\n",
    "        # Convert Numpy array to tensor\n",
    "        Ob = paddle.to_tensor(Observable(self.n))\n",
    "        label_pp = paddle.to_tensor(label)\n",
    "\n",
    "        # According to the randomly initialized parameters theta to build the quantum gate\n",
    "        cir = U_theta(self.theta, n=self.n, depth=self.depth)\n",
    "        Utheta = cir.U\n",
    "        \n",
    "        # Because Utheta is achieved by learning, we compute with row vectors to speed up without affecting the training effect\n",
    "        state_out = matmul(state_in, Utheta) # dimension [-1, 1, 2 ** n]\n",
    "        \n",
    "        # Measure the expected value of Pauli Z operator <Z>\n",
    "        E_Z = matmul(matmul(state_out, Ob), transpose(paddle.conj(state_out), perm=[0, 2, 1]))\n",
    "        \n",
    "        # Mapping <Z> to the estimated value of the label\n",
    "        state_predict = paddle.real(E_Z)[:, 0] * 0.5 + 0.5 + self.bias\n",
    "        loss = paddle.mean((state_predict - label_pp) ** 2)\n",
    "        \n",
    "        # Calculate the accuracy of cross-validation\n",
    "        is_correct = (paddle.abs(state_predict - label_pp) < 0.5).nonzero().shape[0]\n",
    "        acc = is_correct / label.shape[0]\n",
    "\n",
    "        return loss, acc, state_predict.numpy(), cir"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training process\n",
    "\n",
    "After defining all the concepts above, we might take a look at the actual training process."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:03:38.325454Z",
     "start_time": "2021-03-09T04:03:38.299975Z"
    }
   },
   "outputs": [],
   "source": [
    "def heatmap_plot(net, N):\n",
    "    # generate data points x_y_\n",
    "    Num_points = 30\n",
    "    x_y_ = []\n",
    "    for row_y in np.linspace(0.9, -0.9, Num_points):\n",
    "        row = []\n",
    "        for row_x in np.linspace(-0.9, 0.9, Num_points):\n",
    "            row.append([row_x, row_y])\n",
    "        x_y_.append(row)\n",
    "    x_y_ = np.array(x_y_).reshape(-1, 2).astype(\"float64\")\n",
    "\n",
    "    # make prediction: heat_data\n",
    "    input_state_test = paddle.to_tensor(\n",
    "        datapoints_transform_to_state(x_y_, N))\n",
    "    loss_useless, acc_useless, state_predict, cir = net(state_in=input_state_test, label=x_y_[:, 0])\n",
    "    heat_data = state_predict.reshape(Num_points, Num_points)\n",
    "\n",
    "    # plot\n",
    "    fig = plt.figure(1)\n",
    "    ax = fig.add_subplot(111)\n",
    "    x_label = np.linspace(-0.9, 0.9, 3)\n",
    "    y_label = np.linspace(0.9, -0.9, 3)\n",
    "    ax.set_xticks([0, Num_points // 2, Num_points - 1])\n",
    "    ax.set_xticklabels(x_label)\n",
    "    ax.set_yticks([0, Num_points // 2, Num_points - 1])\n",
    "    ax.set_yticklabels(y_label)\n",
    "    im = ax.imshow(heat_data, cmap=plt.cm.RdBu)\n",
    "    plt.colorbar(im)\n",
    "    plt.show()\n",
    "\n",
    "def QClassifier(Ntrain, Ntest, gap, N, D, EPOCH, LR, BATCH, seed_paras, seed_data,):\n",
    "    \"\"\"\n",
    "    Quantum Binary Classifier\n",
    "    \"\"\"\n",
    "        \n",
    "    # Generate data set\n",
    "    train_x, train_y, test_x, test_y = circle_data_point_generator(Ntrain=Ntrain, Ntest=Ntest, boundary_gap=gap, seed_data=seed_data)\n",
    "\n",
    "    # Read the dimension of the training set\n",
    "    N_train = train_x.shape[0]\n",
    "\n",
    "    paddle.seed(seed_paras)\n",
    "    # Define optimization graph\n",
    "    net = Net(n=N, depth=D)\n",
    "\n",
    "    # Generally, we use Adam optimizer to get relatively good convergence\n",
    "    # Of course, it can be changed to SGD or RMSprop\n",
    "    opt = paddle.optimizer.Adam(learning_rate=LR, parameters=net.parameters())\n",
    "\n",
    "    # Initialize the registers to store the accuracy rate and other information\n",
    "    summary_iter, summary_test_acc = [], []\n",
    "\n",
    "    # Optimize iteration\n",
    "    for ep in range(EPOCH):\n",
    "        for itr in range(N_train // BATCH):\n",
    "\n",
    "            # Encode classical data into a quantum state |psi>, dimension [-1, 2 ** N]\n",
    "            input_state = paddle.to_tensor(datapoints_transform_to_state(train_x[itr * BATCH:(itr + 1) * BATCH], N))\n",
    "\n",
    "            # Run forward propagation to calculate loss function\n",
    "            loss, train_acc, state_predict_useless, cir \\\n",
    "                = net(state_in=input_state, label=train_y[itr * BATCH:(itr + 1) * BATCH])\n",
    "            if itr % 50 == 0:\n",
    "                # Calculate the correct rate on the test set test_acc\n",
    "                input_state_test = paddle.to_tensor(datapoints_transform_to_state(test_x, N))\n",
    "                loss_useless, test_acc, state_predict_useless, t_cir \\\n",
    "                    = net(state_in=input_state_test,label=test_y)\n",
    "                print(\"epoch:\", ep, \"iter:\", itr,\n",
    "                      \"loss: %.4f\" % loss.numpy(),\n",
    "                      \"train acc: %.4f\" % train_acc,\n",
    "                      \"test acc: %.4f\" % test_acc)\n",
    "\n",
    "                # Store accuracy rate and other information\n",
    "                summary_iter.append(itr + ep * N_train)\n",
    "                summary_test_acc.append(test_acc)\n",
    "            if (itr + 1) % 151 == 0 and ep == EPOCH - 1:\n",
    "                print(\"The trained circuit:\")\n",
    "                print(cir)\n",
    "\n",
    "            # Run back propagation to minimize the loss function\n",
    "            loss.backward()\n",
    "            opt.minimize(loss)\n",
    "            opt.clear_grad()\n",
    "\n",
    "    # Draw the decision boundary represented by heatmap\n",
    "    heatmap_plot(net, N=N)\n",
    "\n",
    "    return summary_test_acc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2021-03-09T04:04:19.852356Z",
     "start_time": "2021-03-09T04:03:38.709491Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The dimensions of the training set x (200, 2) and y (200, 1)\n",
      "The dimensions of the test set x (100, 2) and y (100, 1) \n",
      "\n",
      "epoch: 0 iter: 0 loss: 0.0318 train acc: 1.0000 test acc: 0.5400\n",
      "epoch: 0 iter: 50 loss: 0.3359 train acc: 0.0000 test acc: 0.8200\n",
      "epoch: 0 iter: 100 loss: 0.0396 train acc: 1.0000 test acc: 0.8700\n",
      "epoch: 0 iter: 150 loss: 0.0952 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 1 iter: 0 loss: 0.1586 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 1 iter: 50 loss: 0.1534 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 1 iter: 100 loss: 0.0624 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 1 iter: 150 loss: 0.0883 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 2 iter: 0 loss: 0.1627 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 2 iter: 50 loss: 0.1378 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 2 iter: 100 loss: 0.0669 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 2 iter: 150 loss: 0.0860 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 3 iter: 0 loss: 0.1658 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 3 iter: 50 loss: 0.1359 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 3 iter: 100 loss: 0.0671 train acc: 1.0000 test acc: 1.0000\n",
      "epoch: 3 iter: 150 loss: 0.0849 train acc: 1.0000 test acc: 1.0000\n",
      "The trained circuit:\n",
      "--Rz(0.542)----Ry(3.456)----Rz(2.699)----*--------------X----Ry(6.153)--\n",
      "                                         |              |               \n",
      "--Rz(3.514)----Ry(1.543)----Rz(2.499)----X----*---------|----Ry(3.050)--\n",
      "                                              |         |               \n",
      "--Rz(5.947)----Ry(3.161)----Rz(3.897)---------X----*----|----Ry(1.583)--\n",
      "                                                   |    |               \n",
      "--Rz(0.718)----Ry(5.038)----Rz(1.348)--------------X----*----Ry(0.030)--\n",
      "                                                                        \n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAATsAAAD5CAYAAABYi5LMAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAfYElEQVR4nO3dW4wkZ3UH8P+pvs19Z70XG4wxhJiLg7BFjE1kocQgHONAEAQJw4OJA1klgjzkAUF4yAMRkiNHIiBusQghluLwAFlwIsfYIgpGEQgMGN8wjlmMsdf2MmvvbaZn+lInD1Wz6Wn3OfVVd8109fT/J7W8O19/VTV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5OIttg8swuU1Td2lCbZIXO3yAx2qvpZJNfGEJE/APAhEfkKkgcTJ1X1qf45InIwbVzbAPARAJ/IWg8RTYYCU0+GbpIdOHeLvE9jbwdwLYBHAawBuGFzQERuB/CBtEv3h0XkrUgukz+vqv+Vcz1EVEIxCv262ChNsqtZc/uJ9yh/J4nIrwH8Mv3rfiQPOmhycJ+VU+9+uVBVD4yyMBG5I11miBVVvSZjedciuVTdbJL9CatJdk+w+6o1111XWYJdLxG5J+Nan0qG+6ycuF/+X96nsUREE4nBjoimQlmD3c3j3gDKjfusnLhfUqW8Z0dEVLSyntkRERVqrMGOJaMmj4hcIyI/S/fZRweMB+1TKk7APtkrIofT/fF9EXn1OLZz3MZ9ZtdbMuoQkpJRW/SUjLpOVV+NJBfvfTu5kZQIrDSRuU+pOIH75GMA7lXV1wC4HklZpKkz7mDHklGTJaTSRMg+peKE7JOLAXwLAFT1YQAvEZFzd3Yzx2/cwY4loyZLyP7KXY2CRhLyef8EwDsBQEQuB3Ahku+STpVxB7tCS0bRtgupNJG7GgWNJOTzvhHAXhG5F0ltuB9jCv8N7fiN/u0sGUXbLqTSRO5qFDSSzM9bVU8hLdohSfmQX6SvqbLjZ3aq+llVvVRVLwXwdQDXp0/wXg+nZFT6382SUf2F/GhnnK1SISJ1JGfct/W95zYE7FMqTOY+EZHldAwAPgDg7jQATpVxp3CwZNQEUdWOiHwISS+AzUoTD/ZVqTD3KRUvcJ+8CsAtItIF8BCA949tg8eI36Agoqkw7gcUREQ7gsGOiKYCgx0RTQUGOyKaCgx2RDQVGOyIaCow2BHRVGCwI6Kp8H9PccXvAbZjYgAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<Figure size 432x288 with 2 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The main program finished running in  35.49316954612732 seconds.\n"
     ]
    }
   ],
   "source": [
    "def main():\n",
    "    \"\"\"\n",
    "    main\n",
    "    \"\"\"\n",
    "    time_start = time.time()\n",
    "    acc = QClassifier(\n",
    "        Ntrain = 200,    # Specify the training set size\n",
    "        Ntest = 100,     # Specify the test set size\n",
    "        gap = 0.5,       # Set the width of the decision boundary\n",
    "        N = 4,           # Number of qubits required\n",
    "        D = 1,           # Circuit depth\n",
    "        EPOCH = 4,       # Number of training epochs\n",
    "        LR = 0.01,       # Set the learning rate\n",
    "        BATCH = 1,       # Batch size during training\n",
    "        seed_paras = 19, # Set random seed to initialize various parameters\n",
    "        seed_data = 2,   # Fixed random seed required to generate the data set\n",
    "    )\n",
    "    \n",
    "    time_span = time.time()-time_start\n",
    "    print('The main program finished running in ', time_span, 'seconds.')\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By printing out the training results, you can see that the classification accuracy in the test set and the data set after continuous optimization has reached $100\\%$."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "_______\n",
    "\n",
    "## References\n",
    "\n",
    "\n",
    "[1] Mitarai, Kosuke, et al. Quantum circuit learning. [Physical Review A 98.3 (2018): 032309.](https://arxiv.org/abs/1803.00745)\n",
    "\n",
    "[2] Farhi, Edward, and Hartmut Neven. Classification with quantum neural networks on near term processors. [arXiv preprint arXiv:1802.06002 (2018).](https://arxiv.org/abs/1802.06002)\n",
    "\n",
    "[3] [Schuld, Maria, et al. Circuit-centric quantum classifiers. [Physical Review A 101.3 (2020): 032308.](https://arxiv.org/abs/1804.00633)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
